﻿using Dm.filter;
using FCT551.Base;
using FCT551.Helper;
using FCT551.Models;
using FCT551.Views;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Xml.Serialization;

namespace FCT551.ViewModels
{
    public class ConfigManageViewModel : NotifyPorperChanged
    {
        public static updateHandler updatemessage;
        private ConfigManageView _configManageView;
        private ObservableCollection<Config> _configs;
        public static ChangeUniformBackgroudHandler _ChangeUniform;
        public static Action InitStation;

        public ObservableCollection<Config> Configs
        {
            set
            {
                _configs = value;
                this.SetProperty();
            }
            get
            {
                return _configs;
            }
        }

        public ConfigManageViewModel(ConfigManageView configManageView)
        {
            _configManageView = configManageView;
            WindowLoadedCommand = new Command() { ExeAction = new Action<object>(WindowLoadedcmd) };
            WindowClosingCommand = new Command() { ExeAction = new Action<object>(WindowClosingcmd) };
            SelectFileCommand = new Command() { ExeAction = new Action<object>(SelectFileCmd) };
            DeleceCommand = new Command() { ExeAction = new Action<object>(DeleceCmd) };
            CreateCommand = new Command() { ExeAction = new Action<object>(CreateCmd) };
            SaveCommand = new Command() { ExeAction = new Action<object>(SaveCmd) };
        }

        #region 绑定方法

        /// <summary>
        /// 退出时执行
        /// </summary>
        /// <param name="obj"></param>
        private async void WindowClosingcmd(object obj)
        {
            try
            {
                //检查用户有没有选中某个配置
                if (Configs != null)
                {
                    var coutList = Configs.Where(p => p.IsUse == true).ToList();
                    if (coutList.Count == 0)
                    {
                        UpdateMessage("用户当前未选择配置！！！", LogLevel.Error);
                    }
                    else
                    {
                    }
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 保存方法
        /// </summary>
        /// <param name="obj"></param>
        private async void SaveCmd(object? obj)
        {
            try
            {
                //写入xml文件
                ConfigsModel configsModel = new();
                configsModel.Users = Global._Users;
                configsModel.Configs = Configs.ToList();
                configsModel.WorkStationName = Global._WorkStationName;
                configsModel.OrderName = Global._WorkStationOrderName;
                var serializer = new XmlSerializer(typeof(ConfigsModel));
                using (var writer = new StreamWriter(Global._ConfigPath))
                {
                    serializer.Serialize(writer, configsModel);
                }
                //更新当前配置列表以及选择的配置文件
                Global._Configs = Configs.ToList();
                var useConfig = Global._Configs.Where(g => g.IsUse == true).ToList();
                if (useConfig.Count > 0)
                {
                    Global._Config = useConfig[0].Clone() as Config;
                    updatemessage("保存成功");

                    //加载测试文件
                    //LoadMethods()放在initSysConfigHelper里，暂时不用这个类下的
                    if (await InitSysConfigHelper.LoadMethods())
                    {
                        UpdateMessage("加载测试文件成功");
                    }
                    else
                    {
                        UpdateMessage("加载测试文件失败", LogLevel.Error);
                    }
                    InitStation.Invoke();
                }
                else
                {
                    UpdateMessage("当前没有选择配置！！！", LogLevel.Error);
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="obj"></param>
        private void CreateCmd(object? obj)
        {
            try
            {
                if (ChooseItem != null)
                {
                    Config? config = ChooseItem.Clone() as Config;
                    int maxConfigId = Configs.Max(s => s.Configid);
                    config.Configid = maxConfigId + 1;
                    Configs.Add(config);
                    updatemessage("添加成功");
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="obj"></param>
        private void DeleceCmd(object? obj)
        {
            try
            {
                if (ChooseItem != null)
                {
                    var configs = Configs.Where(s => s.Configid == ChooseItem.Configid).ToList();
                    if (configs.Count > 1)
                    {
                        updatemessage("删除失败，配置id存在重复", LogLevel.Error);
                    }
                    else
                    {
                        foreach (var cc in configs)
                        {
                            Configs.Remove(cc);
                        }

                        updatemessage("删除成功");
                    }
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 界面加载方法
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void WindowLoadedcmd(object obj)
        {
            try
            {
                if (Global._Configs != null)
                {
                    Configs = new ObservableCollection<Config>(Global._Configs.Clone());
                    foreach (var item in Configs)
                    {
                        item.SelectFileCommand = new Command() { ExeAction = new Action<object>(SelectFileCmd) };
                        item.SelectImageCommand = new Command() { ExeAction = new Action<object>(SelectImageCmd) };
                    }
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 选择测试文件路径
        /// </summary>
        /// <param name="obj"></param>
        private void SelectFileCmd(object obj)
        {
            try
            {
                Config config = obj as Config;
                //选择文件
                var openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestConfig");
                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var person in Configs.Where(p => p.Configid == config.Configid))
                    {
                        person.PathMothedaPath = openFileDialog.FileName;
                    }
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 选择配置对应的产品图片
        /// </summary>
        /// <param name="obj"></param>
        private void SelectImageCmd(object obj)
        {
            try
            {
                Config config = obj as Config;
                //选择文件
                var openFileDialog = new OpenFileDialog();
                openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var person in Configs.Where(p => p.Configid == config.Configid))
                    {
                        person.ProcdutImagePath = openFileDialog.FileName;
                    }
                }
            }
            catch (Exception e)
            {
                UpdateMessage(e.Message, LogLevel.Error);
            }
        }

        #endregion 绑定方法

        #region 初始化命令和参数

        private Command _windowLoadedCommand;

        public Command WindowLoadedCommand
        {
            set
            {
                _windowLoadedCommand = value;
            }
            get
            {
                return _windowLoadedCommand;
            }
        }

        private Command _windowClosingCommand;

        public Command WindowClosingCommand
        {
            set
            {
                _windowClosingCommand = value;
            }
            get
            {
                return _windowClosingCommand;
            }
        }

        private Command _selectFileCommand;

        public Command SelectFileCommand
        {
            set
            {
                _selectFileCommand = value;
            }
            get
            {
                return _selectFileCommand;
            }
        }

        private Command _deleceCommand;

        public Command DeleceCommand
        {
            set
            {
                _deleceCommand = value;
            }
            get
            {
                return _deleceCommand;
            }
        }

        private Command _createCommand;

        public Command CreateCommand
        {
            set
            {
                _createCommand = value;
            }
            get
            {
                return _createCommand;
            }
        }

        private Command _saveCommand;

        public Command SaveCommand
        {
            set
            {
                _saveCommand = value;
            }
            get
            {
                return _saveCommand;
            }
        }

        private Config _chooseItem;

        public Config ChooseItem
        {
            set
            {
                _chooseItem = value;
                this.SetProperty();
            }
            get
            {
                return _chooseItem;
            }
        }

        #endregion 初始化命令和参数

        #region 普通方法

        /// <summary>
        /// 更新日志
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="logLevel"></param>
        private void UpdateMessage(string msg, LogLevel logLevel = LogLevel.Info)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                updatemessage?.Invoke(msg, logLevel);
            });
        }

        #endregion 普通方法
    }
}